package com.jinyu.admin.controller.sys;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import com.jinyu.admin.service.sys.SysRoleService;
import com.jinyu.common.base.ApiRestResponse;
import com.jinyu.dao.entity.sys.SysRole;
import com.jinyu.dao.entity.sys.SysRoleMenu;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yangli
 * @Despriction: 系统角色控制器
 * @Package: com.jinyu.admin.controller.sys
 * @Date:Created in 2022/5/5 20:35
 * @Modify By:
 */
@Slf4j
@RestController
@RequestMapping("/role")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    /**
     *  新增角色接口
     * @param sysRole   角色数据
     * @return  ApiRestResponse
     */
    @PostMapping("/add/1.0")
    public ApiRestResponse<Object> addRole (@RequestBody @Valid SysRole sysRole) {
        log.info("角色信息{}",sysRole.toString());
        int insert = sysRoleService.insert(sysRole);
        return insert > 0 ? ApiRestResponse.ok("新增角色成功") : ApiRestResponse.err("新增角色失败");
    }

    /**
     *  给用户分配角色
     * @param useCode   用户编码
     * @param roleCodes 角色编码
     * @return  ApiRestResponse
     */
    @SaCheckPermission(value = "ADD",orRole = {"super_admin","admin"})
    @GetMapping("/distributionRolesToUser/1.0")
    public ApiRestResponse<Object> distributionRolesToUser (@RequestParam("useCode") String useCode, @RequestParam("roleCodes") String roleCodes) {
        int insert = sysRoleService.distributionRolesToUser(useCode,roleCodes);
        return insert > 0 ? ApiRestResponse.ok("分配角色成功") : ApiRestResponse.err("分配角色失败");
    }

    /**
     *  获取指定用户的角色集合
     * @param useCode   用户编码
     * @return  ApiRestResponse
     */
    @GetMapping("/getRoleListByUserCode/1.0")
    public ApiRestResponse<List<String>> getRoleListByUserCode (@RequestParam("useCode") String useCode) {
        List<String> sysRoleList = sysRoleService.getRoleListByUserCode(useCode);
        return CollUtil.isNotEmpty(sysRoleList) ? ApiRestResponse.ok("获取用户角色成功",sysRoleList) : ApiRestResponse.err("获取用户角色失败",new ArrayList<>());
    }

    /**
     *  分配角色与权限给菜单页面接口
     * @param sysRoleMenu   角色菜单数据
     * @return  ApiRestResponse
     */
    @PostMapping("/distributionRolesPermitToMenu/1.0")
    public ApiRestResponse<Object> distributionRolesPermitToMenu (@RequestBody @Valid SysRoleMenu sysRoleMenu) {
        log.info("角色信息{}",sysRoleMenu.toString());
        int insert = sysRoleService.insertRolesPermitToMenu(sysRoleMenu);
        return insert > 0 ? ApiRestResponse.ok("分配角色与权限给菜单页面成功") : ApiRestResponse.err("分配角色与权限给菜单页面失败");
    }

}
